//index.js
var wxCharts = require('../../utils/wxcharts.js');
var WxPsi = require('../../utils/wxPsi.js');

//获取应用实例
const app = getApp()
var psi;
var lineChart = null;

Page({
  data: {
    everyDayMsg: "",
    userInfo: {},
    hasUserInfo: false,
    width: 420,
    today: "",
    pickerBirthdaySt: "",
    pickerBirthdayEt: "",
    pickerBirthdayDefault: "",
    animationData: '',
    chartHeight: 200,
    hideBanner: true
  },
  onShareAppMessage: function (res) {
    return {
      title: "我的生物钟曲线，你的呢？",
      path: 'pages/index/index',
      imageUrl: '',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  onPullDownRefresh: function () {
    this.renderChart(psi.viewCurrentMonth());
    wx.stopPullDownRefresh()
  },
  like: function (e) {
    if (wx.navigateToMiniProgram) {
      wx.navigateToMiniProgram({
        appId: 'wx18a2ac992306a5a4',
        path: 'pages/apps/largess/detail?accountId=565298',
        //envVersion: 'develop',
        success(res) {
          // 打开成功
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      /*wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })*/
      console.warn("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。")
      wx.redirectTo({
        url: '/pages/like/like'
      })
    }
  },
  toIntroduce: function () {
    wx.navigateTo({
      url: '/pages/psi/introduce'
    })
  },
  touchHandler: function (e) {
    lineChart.showToolTip(e, {
      format: function (item, category) {
        return category + '日 ' + item.name + ': ' + item.data
      }
    });
  },
  createSimulationData: function () {
    var categories = [];
    var data = [];
    for (var i = 0; i < psi.lastDay; i++) {
      categories.push((i + 1));
    }
    return {
      categories: categories,
      data: data
    }
  },
  viewCurrentMonth: function () {
    this.renderChart(psi.viewCurrentMonth());
  },
  viewPreMonth: function () {
    this.renderChart(psi.viewPreMonth());
  },
  viewNextMonth: function () {
    this.renderChart(psi.viewNextMonth());
  },
  bindDateChange: function (e) {
    var storeUserData = {
      birthday: e.detail.value
    }

    try {
      wx.setStorageSync('userData', storeUserData);
    } catch (e) {
    }

    var userData = {
      birthday: new Date(storeUserData.birthday)
    }

    psi = new WxPsi.Psi(userData);
    this.renderChart(psi.calcPsis())
  },
  updateData: function () {
    var simulationData = this.createSimulationData();
    var series = [];
    lineChart.updateData({
      categories: simulationData.categories,
      series: series
    });
  },
  createSeriesData: function (chartDatas) {
    var series = [{
      name: '体力',
      data: chartDatas[0],
      color: '#d95850',
      format: function (val, name) {
        return val.toFixed(0);
      }
    }, {
      name: '情绪',
      data: chartDatas[1],
      color: '#32a487',
      format: function (val, name) {
        return val.toFixed(0);
      }
    }, {
      name: '智力',
      data: chartDatas[2],
      color: '#ffb248',
      format: function (val, name) {
        return val.toFixed(0);
      }
    }];
    return series;
  },
  renderChart: function (chartDatas) {
    var windowWidth = 420;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }

    var simulationData = this.createSimulationData();
    lineChart = new wxCharts({
      canvasId: 'psiCanvas',
      type: 'line',
      categories: simulationData.categories,
      animation: false,
      series: this.createSeriesData(chartDatas),
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        title: '',//psi.displayViewYearMonth,
        titleFontColor: '#d95850',
        format: function (val) {
          return val.toFixed(0);
        },
        min: -100,
        max: 100
      },

      width: windowWidth,
      height: this.data.chartHeight,
      dataLabel: false,
      extra: {
        lineStyle: 'curve'
      }
    });

    lineChart.setViewDate(psi.viewDate);
    lineChart.setTodayPsiValues(psi.todayPsiValues);
    this.setData({
      everyDayMsg: psi.everyDayMsg(),
      userData: psi.userData,
      today: psi.todayTip,
      width: windowWidth,
      pickerBirthdaySt: psi.pickerBirthdaySt,
      pickerBirthdayEt: psi.pickerBirthdayEt,
      pickerBirthdayDefault: psi.pickerBirthdayDefault
    })

    var that = this;
    var isHide = true;
    if (app.globalData.version === "1.0") {
      wx.request({
        url: 'https://api.it120.cc/d1e3eff905c3d15348ab525d8201d8ac/banner/list',
        success: function (res) {
          if (res.data.code == 404) {
            isHide = true;
          } else {
            if (res.data.data && res.data.data.length > 0) {
              var banner = res.data.data[0];
              if (banner) {
                isHide = banner.paixu >= 1;
              }
            }
          }
          that.setData({ hideBanner: isHide });
        }
      })
    } else {
      that.setData({ hideBanner: false });
    }
  },
  onLoad: function (e) {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

    var userData = {
      birthday: new Date('1981-11-20')
    }

    try {
      var value = wx.getStorageSync('userData')
      if (value) {
        userData.birthday = new Date(value.birthday);
      }
    } catch (e) {
      // Do something when catch error
    }
    psi = new WxPsi.Psi(userData);
    this.renderChart(psi.calcPsis())

    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })

    this.animation = animation;
    var that = this;
    setInterval(function () {
      animation.scale(1.3, 1.3).step().scale(1, 1).step()
      that.setData({
        animationData: animation.export()
      })
    }, 500);
  }
});
